package com.wangl.spring.utils;

import com.intellij.lang.properties.IProperty;
import com.intellij.lang.properties.psi.PropertiesFile;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.search.FileTypeIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.wangl.spring.suggestion.filetype.SpringConfigurationPropertiesFileType;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName PropertiesFileUtil
 * @Description TODO
 * @Author wangl
 * @Date 2023/8/7 16:45
 */
public class PropertiesFileUtil {

    public static Set<PsiElement> findByKey(String placeholder, GlobalSearchScope scope, Project project) {
        Collection<VirtualFile> propertiesFiles = FileTypeIndex.getFiles(SpringConfigurationPropertiesFileType.INSTANCE, scope);
        Map<String, Set<PsiElement>> map = new ConcurrentHashMap<>();
        for (VirtualFile propertiesVirtualFile : propertiesFiles) {
            PsiManager psiManager = PsiManager.getInstance(project);
            PsiFile psiFile = psiManager.findFile(propertiesVirtualFile);
            PropertiesFile propertiesFile = (PropertiesFile) psiFile;
            if (Objects.isNull(propertiesFile)){
                continue;
            }
            List<IProperty> properties = propertiesFile.getProperties();
            for (IProperty property : properties) {
                String key = property.getKey();
                map.computeIfAbsent(key, k -> new HashSet<>()).add(property.getPsiElement());
            }
        }
        return map.getOrDefault(placeholder, Collections.emptySet());
    }
}
